$(function() {
	/*
	 * 初始化 loading
	 */
	var loading = $('.overlay').hide();

	/*
	 * 图片上传
	 */
	var avatarUploader = new PicUploader({
		before: function() {
			loading.show();	
		},
		success: function(obj) {
			var picUrl = obj['data'];
			$('#avatar-btn').css('background-image','url('+picUrl+')');
			$('#avatar-url').val(picUrl);
			loading.hide();
		}
	});
	$('#avatar-btn').on('click',function(){
		avatarUploader.start();
	});

	/*
	 * 行政地区选择器初始化
	 */
	$.getJSON(staticUrl+'/bootstrap-chinese-region/dist/sql_areas.json',function(data){
		for (var i = 0; i < data.length; i++) {
			var area = {id:data[i].id,name:data[i].cname,level:data[i].level,parentId:data[i].upid};
			data[i] = area;
		}
		$('.bs-chinese-region').each(function(){
			var $this = $(this);
			$this.attr('data-result',$this.find('input.address').val());
			$this.chineseRegion('source',data);
		});
	});

	$('.bs-chinese-region').on('changed.bs.chinese-region',function(e,areas){
		  //areas是已选择的地区数据，按先选择的在最前的方式排序。
		  $(this).attr('data-result',areas[areas.length-1]['id']);
	});
	
	/*
	 * 保存
	 */
	$('#save-btn').on('click',function(){
		$('.overlay').show();
		gatherDatas();
		cAjax({
			url: 'edit',
			data: gatherDatas(),
			dataType: 'json',
			cache: false,
			success: function(obj) {
				greeting({msg:'保存成功'});
				$('.overlay').hide();
		   	}
		});

		function gatherDatas() {
			var formData = {
				uid: $('#uid').text(),
			};
			$('.content :input[name]').each(function(){
				var $this = $(this);
				formData[$this.attr('name')] = $this.val();
			});
			var oftenCities = [];
			$('.bs-chinese-region').each(function(){
				oftenCities.push($(this).attr('data-result'));
			});
			formData['oftenCities'] = oftenCities.toString();
			return formData;
		}

	});	
});
